<script>
import { fabric } from "fabric";

export default {
  name: "FabricDemo",
  data() {
    return {
      popover: false,
      canvas: null,
      fontSize: "字体大小",
      isBold: false,
      align: "",
      fontColor: "",
    };
  },
  methods: {
    handleCommand(command) {
      this.fontSize = command + "px";
      this.setSelectedProperty("fontSize", command);
    },
    setAlign(val) {
      this.align = val;
      this.setSelectedProperty("textAlign", this.align);
    },
    setBold() {
      this.isBold = !this.isBold;
      this.setSelectedProperty("fontWeight", this.isBold ? 600 : 500);
    },
    setSelectedProperty(name, value) {
      const object = this.canvas.getActiveObject();
      if (!object) return;
      object.set(name, value).setCoords();
      this.canvas.renderAll();
    },
    unselectFabricItem() {
      this.fontSize = "字体大小";
      this.isBold = false;
      this.align = "";
      this.fontColor = "";
    },
    selectFabricItem() {
      const selected = this.canvas.getActiveObject();
      if (selected.type === "textbox") {
        this.align = selected.textAlign;
        this.fontSize = selected.fontSize + "px";
        this.fontColor = selected.fill;
        if (selected.fontWeight > 500) this.isBold = true;
      } else {
        this.unselectFabricItem()
      }
    },
    addParameter() {
      let text = new fabric.Textbox("证书名称", {
        left: 0,
        top: 0,
        fontFamily: "Comic Sans", //字体
        fontSize: 20, //字号
        fontStyle: "normal",
        lineHeight: 1.5, //行高
      });
      this.canvas.add(text);
    },
    setBackgroundImage(e) {
      fabric.Image.fromURL(e.target.src, (img) => {
        img.set({
          // 通过scale来设置图片大小，这里设置和画布一样大
          scaleX: this.canvas.width / img.width,
          scaleY: this.canvas.height / img.height,
        });
        // 设置背景
        this.canvas.setBackgroundImage(
          img,
          this.canvas.renderAll.bind(this.canvas)
        );
        this.canvas.renderAll();
      });
    },
  },
  mounted() {
    const timer = setTimeout(() => {
      const ele = document.querySelector("canvas");
      const parent = document.querySelector(".left");
      ele.width = parent.offsetWidth - 16 * 2;
      ele.height = parent.offsetHeight - 16 * 3 - 32;
      this.canvas = new fabric.Canvas(ele);
      this.canvas.selection = true;
      this.canvas.loadFromJSON(
        '{"version":"5.3.0","objects":[{"type":"rect","version":"5.3.0","originX":"left","originY":"top","left":229,"top":163,"width":200,"height":200,"fill":"green","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"rx":0,"ry":0},{"type":"image","version":"5.3.0","originX":"left","originY":"top","left":125,"top":-48,"width":1366,"height":1366,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.2,"scaleY":0.2,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"http://localhost:8080/img/3.6c5868fe.png","crossOrigin":null,"filters":[]},{"type":"textbox","version":"5.3.0","originX":"left","originY":"top","left":189,"top":301,"width":567.43,"height":226,"fill":"rgb(0,0,0)","stroke":"#c3bfbf","strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"fontFamily":"Comic Sans","fontWeight":800,"fontSize":50,"text":"大家好~这里是前埔寨\\n我是荣顶~\\n一个要成为开发王的男人!","underline":true,"overline":true,"linethrough":false,"textAlign":"center","fontStyle":"italic","lineHeight":1.5,"textBackgroundColor":"#91A8D0","charSpacing":0,"styles":[],"direction":"ltr","path":null,"pathStartOffset":0,"pathSide":"left","pathAlign":"baseline","minWidth":20,"splitByGrapheme":false}],"backgroundImage":{"type":"image","version":"5.3.0","originX":"left","originY":"top","left":0,"top":0,"width":1366,"height":1366,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.59,"scaleY":0.59,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"http://localhost:8080/img/1.f72a24e4.png","crossOrigin":null,"filters":[]}}',
        () => {
          this.canvas.renderAll();
        }
      );
      this.canvas.on("selection:created", () => {
        this.selectFabricItem();
      });
      this.canvas.on("selection:updated", () => {
        this.selectFabricItem();
      });
      this.canvas.on("selection:cleared", () => {
        this.unselectFabricItem();
      });
      clearTimeout(timer);
    }, 100);
  },
};
</script>

<template>
  <div>
    <el-form size="small">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="证书名称">
            <el-input></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证书名称">
            <el-select style="width: 100%"></el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <label class="el-form-item__label">配置证书</label>
    </div>
    <div class="certification-box">
      <div class="left">
        <div class="toolbar">
          <el-popover
            v-model="popover"
            placement="bottom-start"
            trigger="click"
            :visible-arrow="false"
          >
            <div class="params-box">
              <div
                class="params-item"
                v-for="n in 13"
                :key="n"
                @click="addParameter"
              >
                证书名称
              </div>
            </div>
            <el-button slot="reference" size="small">动态参数</el-button>
          </el-popover>
          <div class="font">
            <div
              :class="{ active: isBold }"
              class="button"
              style="font-weight: 600"
              @click="setBold"
            >
              B
            </div>
            <el-dropdown trigger="click" @command="handleCommand">
              <div class="button">
                {{ fontSize }}<i class="el-icon-arrow-down el-icon--right"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="n in 16"
                  :key="n"
                  :command="10 + n * 2"
                >
                  {{ 10 + n * 2 }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-color-picker
              color-format="rgb"
              size="small"
              v-model="fontColor"
              @change="setSelectedProperty('fill', fontColor)"
            ></el-color-picker>
            <div
              :class="{ active: align === 'left' }"
              class="button"
              @click="setAlign('left')"
            >
              <img alt="" src="../assets/alignLeft.png" />
            </div>
            <div
              :class="{ active: align === 'center' }"
              class="button"
              @click="setAlign('center')"
            >
              <img alt="" src="../assets/alignCenter.png" />
            </div>
            <div
              :class="{ active: align === 'right' }"
              class="button"
              @click="setAlign('right')"
            >
              <img alt="" src="../assets/alignRight.png" />
            </div>
          </div>
        </div>
        <canvas></canvas>
      </div>
      <div class="right">
        <img
          v-for="n in 5"
          :key="n"
          alt=""
          :src="require(`../assets/${n}.png`)"
          @click="setBackgroundImage"
        />
        <div class="upload">
          <i class="el-icon-upload"></i>
          <div>上传新的证书底图</div>
          <div style="color: #86909c; font-size: 13px; margin-top: 10px">
            <div>建议尺寸：297×210mm;</div>
            <div>格式：PNG、JPG、JPEG;</div>
            <div>图片大小：≤2M</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
* {
  box-sizing: border-box;
}

.certification-box {
  width: 100%;
  display: flex;
  margin-top: 16px;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
  max-height: 60vh;

  .left {
    width: calc(100% - 360px);
    border-right: 1px solid #e5e6eb;
    padding: 16px;

    .toolbar {
      width: 100%;
      display: flex;
      align-items: center;
      column-gap: 16px;

      .font {
        height: 32px;
        display: flex;
        align-items: center;
        column-gap: 8px;

        .button {
          height: 32px;
          padding: 0 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          border: 1px solid #e5e6eb;
          border-radius: 4px;

          img {
            height: 14px;
            object-fit: cover;
          }
        }

        .active {
          border-color: #000000;
          background: rgb(235, 235, 235);
        }
      }
    }

    canvas {
      margin-top: 16px;
    }
  }

  .right {
    width: 360px;
    overflow: auto;
    padding: 8px 16px;

    img {
      width: 100%;
      object-fit: cover;
      margin: 10px 0;
      cursor: pointer;
      border-radius: 4px;
    }

    .upload {
      width: 100%;
      padding: 16px;
      border: 1px dashed #e5e6eb;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      user-select: none;

      i {
        font-size: 48px;
        color: #c9cdd4;
      }
    }
  }
}

.params-box {
  width: 320px;
  display: flex;
  flex-wrap: wrap;
  row-gap: 16px;
  column-gap: 16px;

  .params-item {
    width: calc((100% - 32px) / 3);
    padding: 4px 0;
    border: 1px solid #86909c;
    border-radius: 4px;
    user-select: none;
    cursor: pointer;
    text-align: center;
    font-size: 13px;
    color: #86909c;

    &:hover {
      border-color: #ef3a29;
      color: #ef3a29;
    }
  }
}
</style>
